package br.usjt.mazerobot.comunicacao;

import br.usjt.mazerobot.Configuracao;
import br.usjt.mazerobot.commons.comunicacao.Encoder;
import br.usjt.mazerobot.commons.comunicacao.Pacote;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import lejos.nxt.LCD;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
import lejos.nxt.comm.NXTConnection;

public class ComunicadorBluetooth implements Comunicador {

    private BTConnection connection;
    private DataInputStream inputStream;
    private DataOutputStream outputStream;
    private Encoder encoder;

    public ComunicadorBluetooth() {
        aguardarConexao();
        try {
            Thread.sleep(2000);
            LCD.clear();
            encoder = new Encoder();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }

    public final void aguardarConexao() {

        Thread visor = new Thread(new Runnable() {

            public void run() {
                while (!Thread.interrupted()) {
                    try {
                        LCD.clear();
                        LCD.drawString("Aguardando", 4, 3);
                        LCD.drawString("Conexao.", 4, 4);
                        LCD.refresh();
                        Thread.sleep(1000);
                        LCD.drawString("Aguardando", 4, 3);
                        LCD.drawString("Conexao..", 4, 4);
                        LCD.refresh();
                        Thread.sleep(1000);
                        LCD.drawString("Aguardando", 4, 3);
                        LCD.drawString("Conexao...", 4, 4);
                        LCD.refresh();
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        Thread.currentThread().interrupt();
                    }
                }
                LCD.clear();
                LCD.drawString("Conectado.", 3, 4);
            }
        });
        visor.start();//Inicia a thread que faz a animação "Aguardando conexão"

        connection = Bluetooth.waitForConnection(Configuracao.BLUETOOTH_TIMEOUT, NXTConnection.PACKET, Configuracao.BLUETOOTH_PIN);
        visor.interrupt(); //Encerra a thread que faz a animação "Aguardando conexão"

        try {
            Thread.sleep(2000);
            LCD.clear();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

        inputStream = connection.openDataInputStream();
        outputStream = connection.openDataOutputStream();
    }

    public void desconectar() {

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
            }
        }

        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
            }
        }

        if (connection != null) {
            connection.close();
        }
    }

    public synchronized void enviar(Pacote pacote) {
        try {
            outputStream.write(pacote.getDados());
            outputStream.flush();
        } catch (IOException ex) {
        }
    }

    public Pacote receber() {

        Pacote pacote = new Pacote();
        byte[] dados = new byte[16];
        try {
            inputStream.read(dados);
            pacote = new Pacote(dados);
        } catch (IOException ex) {
        }
        return pacote;
    }

    public void enviarLog(String info) {

        Pacote[] pacotes = encoder.codificar(info);

        for (Pacote p : pacotes) {
            enviar(p);
        }
    }

    public int getIntensidadeSinalBluetooth() {
        return connection.getSignalStrength();
    }
}
